/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2010 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id: HeatingRulesTestCase.java 112 2010-06-15 15:50:31Z guillaume.sauthier $
 * --------------------------------------------------------------------------
 */


package org.osami.gateway.rules.heating;

import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.runtime.KnowledgeSessionConfiguration;
import org.drools.runtime.StatefulKnowledgeSession;
import org.drools.runtime.conf.ClockTypeOption;
import org.drools.time.SessionPseudoClock;
import org.osami.gateway.profile.gateway.GatewayProfile;
import org.osami.gateway.profile.heating.HeatingProfile;
import org.osami.gateway.rules.heating.internal.Activator;
import org.osami.gateway.type.Temperature;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

/**
 * A {@code HeatingRulesTestCase} is ...
 *
 * @author Guillaume Sauthier
 */
public class HeatingRulesTestCase extends AbstractRulesTestCase {

    private StatefulKnowledgeSession session;

    private SessionPseudoClock clock;

    private MockEventAdmin eventAdmin;

    @BeforeMethod
    private void setUp() throws Exception {
        URL drlUrl = getClass().getResource("OsamiHeatingRules.drl");
        KnowledgeBase base = buildKnowledgeBase(Collections.singleton(drlUrl));

        KnowledgeSessionConfiguration configuration = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
        configuration.setOption(ClockTypeOption.get("pseudo"));

        session = base.newStatefulKnowledgeSession(configuration, null);

        clock = (SessionPseudoClock) session.getSessionClock();

        eventAdmin = new MockEventAdmin();
        session.setGlobal(Activator.EVENT_ADMIN, eventAdmin);

        // Static facts configuration

        GatewayProfile gateway = new GatewayProfile();
        gateway.setIdentifier("B1-163");
        session.insert(gateway);

        HeatingProfile profile = new HeatingProfile();
        profile.setTargetTemperature(20);
        session.insert(profile);

        Assert.assertNotNull(session);
    }

    @Test
    public void testAverageTemperatureIsTooHighActivation() throws Exception {

        Temperature t1 = new Temperature(18);
        session.insert(t1);

        Temperature t2 = new Temperature(20);
        session.insert(t2);

        Temperature t3 = new Temperature(22);
        session.insert(t3);

        Temperature t4 = new Temperature(24);
        session.insert(t4);

        int nbRulesFired = session.fireAllRules();

        Assert.assertEquals(nbRulesFired, 1);

        Assert.assertEquals(eventAdmin.postedEvents.size(), 1);
        Event event = eventAdmin.postedEvents.get(0);
        Assert.assertEquals(event.getProperty("source"), "B1-163");
        Assert.assertEquals(event.getProperty("type"), "HeatingAlarm");
        Assert.assertEquals(event.getProperty("threshold"), 20d);
        Assert.assertEquals(event.getProperty("temperature"), 21d);

    }

    @Test
    public void testAverageTemperatureIsTooHighActivationWithoutOldEvents() throws Exception {

        // Only the 2 last events should be used when computing
        // average value in the last 5 minutes events

        Temperature t1 = new Temperature(18);
        session.insert(t1);

        Temperature t2 = new Temperature(20);
        session.insert(t2);

        // Advance in time (6 minutes) so that previously injected facts will
        // not be used in the accumulate function
        // TimeUnit.MINUTES is only available in Java 6 :'(
        clock.advanceTime(360, TimeUnit.SECONDS);

        Temperature t3 = new Temperature(22);
        session.insert(t3);

        Temperature t4 = new Temperature(24);
        session.insert(t4);

        int nbRulesFired = session.fireAllRules();

        Assert.assertEquals(nbRulesFired, 1);

        Assert.assertEquals(eventAdmin.postedEvents.size(), 1);
        Event event = eventAdmin.postedEvents.get(0);
        Assert.assertEquals(event.getProperty("source"), "B1-163");
        Assert.assertEquals(event.getProperty("type"), "HeatingAlarm");
        Assert.assertEquals(event.getProperty("threshold"), 20d);
        Assert.assertEquals(event.getProperty("temperature"), 23d);

    }


    @Test
    public void testAverageTemperatureIsTooHighNotActivated() throws Exception {

        Temperature t1 = new Temperature(18);
        session.insert(t1);

        Temperature t2 = new Temperature(16);
        session.insert(t2);

        int nbRulesFired = session.fireAllRules();

        Assert.assertEquals(nbRulesFired, 0);

    }


    private class MockEventAdmin implements EventAdmin {

        public List<Event> postedEvents = new ArrayList<Event>();
        public List<Event> sendEvents = new ArrayList<Event>();

        public void postEvent(Event event) {
            postedEvents.add(event);
        }

        public void sendEvent(Event event) {
            sendEvents.add(event);
        }
    }
}
